package com.edu.policy.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.policy.common.service.RedisService;
import com.edu.policy.domin.FunctionParseResult;
import com.edu.policy.domin.PageDto;
import com.edu.policy.model.DmsFunctionCodes;
import com.edu.policy.service.AppDmsFuncService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AppDmsFuncServiceImpl extends DmsFunctionCodesServiceImpl implements AppDmsFuncService {
    private final RedisService redisService;
    @Override
    public PageDto<DmsFunctionCodes> list(Integer pageSize, Integer pageNum) {
        PageDto<DmsFunctionCodes> result = new PageDto<>();
        Page<DmsFunctionCodes> page = Page.of(pageNum, pageSize);
        Page<DmsFunctionCodes> tempResult = lambdaQuery()
                .page(page);
        result.setList(tempResult.getRecords());
        result.setPages(tempResult.getPages());
        result.setPageSize(tempResult.getSize());
        result.setTotal(tempResult.getTotal());
        result.setCurrentPage(tempResult.getCurrent());
        return result;
    }

    @Override
    public List<FunctionParseResult> parse(String deviceId, String funcCode) {
        String redisKey = "modbus:latest:" + deviceId + ":" + funcCode; // Redis Key
        // 从 Redis 中获取最新的元素modbus:latest:0x01:0x01
        Object result = redisService.hGetAll(redisKey);
        List<FunctionParseResult> list = new ArrayList<>();
        if (result != null) {
            @SuppressWarnings("unchecked")
            Map<String, String> latestDataFromRedis = (Map<String, String>) result;
            if (latestDataFromRedis.isEmpty()) return list;
            // 取出具体字段
            String rawData = latestDataFromRedis.get("raw_data");
            String timestamp = latestDataFromRedis.get("timestamp");
            String resultData = latestDataFromRedis.get("result");
            FunctionParseResult parseResult = new FunctionParseResult();
            parseResult.setSourceCode(rawData);
            parseResult.setCreateTime(timestamp);
            parseResult.setFuncCode(funcCode);
            parseResult.setDeviceId(deviceId);
            parseResult.setParseData(resultData);
            list.add(parseResult);
        }

        return list;
    }
}
